package com.aircms.service.impl;

import com.aircms.common.ServerResponse;
import com.aircms.dao.RoleMapper;
import com.aircms.dao.RolePermissionMapper;
import com.aircms.pojo.Role;
import com.aircms.pojo.validation.BaseQueryFieldsValidation;
import com.aircms.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author air
 * @create 2018-07-03 下午2:34
 */
@Service("iRoleService")
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    public ServerResponse index(BaseQueryFieldsValidation baseQueryFields, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Role> role=roleMapper.selectALl(baseQueryFields);
        PageInfo pageInfo=new PageInfo(role);
        return ServerResponse.response(pageInfo);
    }


    public ServerResponse store(Role role){
        if(roleMapper.countByName(role.getName())>0){
            return ServerResponse.response("",-2,role.getName()+"已存在");
        }
        roleMapper.insertSelective(role);
        return ServerResponse.response();
    }


    /**
     * 更新角色数据
     * @param role
     * @return
     */
    public ServerResponse update(Role role){
        if(roleMapper.countByName(role.getName())>0){
            return ServerResponse.response("",-2,role.getName()+"已存在");
        }
        if(roleMapper.updateByPrimaryKeySelective(role)<1){
            return  ServerResponse.response("",-2,"修改失败");
        }
        return  ServerResponse.response();
    }

    /**
     * 删除角色，并删除角色所有权限
     * @param id
     * @return
     */
    public ServerResponse destroy(Integer id){
        if(roleMapper.setStatus(id,-1)<1){
            return  ServerResponse.response("",-2,"id 不存在");
        }
        // 删除角色所有权限
        rolePermissionMapper.deleteByRoleId(id);
        return ServerResponse.response();
    }

    public ServerResponse getAllUsAbleRole(){
        return ServerResponse.response( roleMapper.selectAllUsableRole());
    }
}
